<template>
  <!-- 诊断记录 -->
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"
              :filter-node-method="filterNodeMethod" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud :option="option" :search.sync="search" :table-loading="loading" :data="data" ref="crud" v-model="form"
          :permission="permissionList" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave"
          :before-open="beforeOpen" :page.sync="page" @search-change="searchChange" @search-reset="searchReset"
          @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
          @refresh-change="refreshChange" @on-load="onLoad">
          <template slot="reportButton" slot-scope="scope">
            <el-button type="text" size="small" :value="scope.row.reportButton"
              @click="viewCheckReport(scope.row)">查看</el-button>
          </template>
          <template slot="prescriptionButton" slot-scope="scope">
            <el-button type="text" size="small" :value="scope.row.prescriptionButton"
              @click="viewPrescription(scope.row)">查看</el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text" size="small" icon="el-icon-view" @click.stop="handleDetail(scope.row)">详情
            </el-button>
            <el-button type="text" size="small" icon="el-icon-info" @click.stop="handleBuildCase(scope.row)">形成案例
            </el-button>
          </template>

        </avue-crud>

      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import { exportBlob } from "@/api/common";
import { getRoleTree } from "@/api/system/role";
import { mapGetters } from "vuex";
import website from '@/config/website';
import { getToken } from '@/util/auth';
import { downloadXls } from "@/util/util";
import { dateNow } from "@/util/date";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import func from "@/util/func";
import { getList, getDetail, add, update, remove } from "@/api/infoManagement/patientFile";
import {
  getDeptLazyTree,
} from "@/api/system/dept";
import { getAge } from '@/util/date.js'

export default {
  data() {
    return {
      form: {},
      search: {},
      roleBox: false,
      excelBox: false,
      platformBox: false,
      initFlag: true,
      selectionList: [],
      query: {},
      loading: true,
      platformLoading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      platformPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        roleTree: [],
        deptTree: [],
      },
      roleGrantList: [],
      roleTreeObj: [],
      treeDeptId: '',
      treeData: [],
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'id',
          children: 'children'
        }
      },
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: 120,
        // searchShowBtn:false,
        dialogClickModal: false,

        // dialogType: 'drawer',

        column: [
          {
            label: "患者姓名",
            prop: "name",
            search: true,

          },
          {
            label: "性别",
            prop: "sex",
            type: "select",
            search: true,
            props: {
              label: 'name',
              value: 'code'
            },
            dicData: [{
              name: '男',
              code: 1
            }, {
              name: '女',
              code: 0
            }],
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]
          },
          {
            label: "出生日期",
            prop: "birthday",
            type: 'date',
            hide: true,
            valueFormat: 'yyyy-MM-dd',
          },
          {
            label: "民族",
            prop: "nation",
            hide: true,
          },
          {
            label: "身份证号",
            prop: "nation",
            hide: true,
          },
          {
            label: "身高",
            prop: "nation",
            hide: true,
          },
          {
            label: "体重",
            prop: "nation",
            hide: true,
          }, {
            label: "年龄",
            prop: "birthday",
            search: true,
            formatter(val, value) {
              return getAge(value)
            }
          },
          {
            label: "联系人",
            prop: "nation",
            hide: true,
          },
          {
            label: "联系电话",
            prop: "nation",
            hide: true,
          },



          {
            label: '建档时间',
            prop: 'createTime',
            type: 'datetime',
            addDisplay: false,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            rules: [
              {
                required: true,
                message: '请选择',
                trigger: 'blur'
              }
            ]

          },
          {
            label: "常住地址",
            prop: "address",
            type: "textarea",
            span: 24,
            minRows: 6,

          },
          {
            label: "状态",
            prop: "status",
            type: "select",
            search: true,
            props: {
              label: 'name',
              value: 'code'
            },
            dicData: [{
              name: '待检查',
              code: 1
            }, {
              name: '待诊断',
              code: 2
            }, {
              name: '待复查',
              code: 3
            }, {
              name: '康复中',
              code: 4
            }, {
              name: '已康复',
              code: 5
            }],
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]
          },
          {
            label: "检查报告",
            prop: "reportButton",
            type: 'url',
            slot: false,
          },
          {
            label: "医嘱处方",
            prop: "prescriptionButton",
            type: 'url',
            slot: false,
          },
        ]

      },
      data: [],


    };
  },
  watch: {

  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.user_add, false),
        // viewBtn: this.vaildData(this.permission.user_view, false),
        // delBtn: this.vaildData(this.permission.user_delete, false),
        // editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },
    platformPermissionList() {
      return {
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    if (!website.tenantMode) {
      this.initData(website.tenantId);
    }
  },
  methods: {
    handleDetail(row) {
      this.$router.push({
        path: '/patientFile/detail',
        query: {
          id: row.id,
          title: '档案详情'
        },
      })
    },
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    handleBuildCase(row) {
      const item = {
        id: row.id,
        typicalCase: 1
      }
      //形成案例
      update(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
      });
    },
    //报告
    viewCheckReport(row) {
      this.$router.push({
        path: '/diagnosticRecordReport',
        query: {
          id: row.id,
        },
      })
    },
    //处方
    viewPrescription(row) {
      this.$router.push({
        path: '/diagnosisRecordPrescriptionDetail',
        query: {
          id: row.id,
        },
      })
    },
    initData(tenantId) {
      // getZhenDuanTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "roleId");
      //   column.dicData = res.data.data;
      // });
      // getDeptTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "deptId");
      //   column.dicData = res.data.data;
      // });
      // getPostList(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "postId");
      //   column.dicData = res.data.data;
      // });
    },
    nodeClick(data) {
      this.treeDeptId = data.key;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      grant(this.ids, roleList).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      row.deptId = row.deptId.join(",");
      row.roleId = row.roleId.join(",");
      row.postId = row.postId.join(",");
      add(row).then(() => {
        this.initFlag = false;
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      row.deptId = row.deptId.join(",");
      row.roleId = row.roleId.join(",");
      row.postId = row.postId.join(",");
      update(row).then(() => {
        this.initFlag = false;
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.query = {};
      this.treeDeptId = '';
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置为123456?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.roleTreeObj = [];
      if (this.selectionList.length === 1) {
        this.roleTreeObj = this.selectionList[0].roleId.split(",");
      }
      getRoleTree().then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
      });
    },
    handlePlatform() {
      this.platformBox = true;
    },
    handleLock() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号解封？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return unlock(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleExport() {
      const account = func.toStr(this.search.account);
      const realName = func.toStr(this.search.realName);
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        NProgress.start();
        exportBlob(`/api/blade-user/export-user?${this.website.tokenHeader}=${getToken()}&account=${account}&realName=${realName}`).then(res => {
          downloadXls(res.data, `用户数据表${dateNow()}.xlsx`);
          NProgress.done();
        })
      });
    },
    handleTemplate() {
      exportBlob(`/api/blade-user/export-template?${this.website.tokenHeader}=${getToken()}`).then(res => {
        downloadXls(res.data, "用户数据模板.xlsx");
      })
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          // if (this.form.hasOwnProperty("deptId")) {
          //   this.form.deptId = this.form.deptId.split(",");
          // }
          // if (this.form.hasOwnProperty("roleId")) {
          //   this.form.roleId = this.form.roleId.split(",");
          // }
          // if (this.form.hasOwnProperty("postId")) {
          //   this.form.postId = this.form.postId.split(",");
          // }
        });
      }
      this.initFlag = true;
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, {
        createDept: this.treeDeptId
      })).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    platformRowUpdate(row, index, done, loading) {
      updatePlatform(row.id, row.userType, row.userExt).then(() => {
        this.platformOnLoad(this.platformPage);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    platformBeforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUserPlatform(this.platformForm.id).then(res => {
          this.platformForm = res.data.data;
        });
      }
      done();
    },
    platformSearchReset() {
      this.platformQuery = {};
      this.platformOnLoad(this.platformPage);
    },
    platformSearchChange(params, done) {
      this.platformQuery = params;
      this.platformPage.currentPage = 1;
      this.platformOnLoad(this.platformPage, params);
      done();
    },
    platformSelectionChange(list) {
      this.platformSelectionList = list;
    },
    platformSelectionClear() {
      this.platformSelectionList = [];
      this.$refs.platformCrud.toggleSelection();
    },
    platformCurrentChange(currentPage) {
      this.platformPage.currentPage = currentPage;
    },
    platformSizeChange(pageSize) {
      this.platformPage.pageSize = pageSize;
    },
    platformRefreshChange() {
      this.platformOnLoad(this.platformPage, this.platformQuery);
    },
    platformOnLoad(page, params = {}) {
      this.platformLoading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.createDept).then(res => {
        const data = res.data.data;
        this.platformPage.total = data.total;
        this.platformData = data.records;
        this.platformLoading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}
</style>
